<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>表单校验</title>
  <style>
    form {
      width: 400px;
      border: 10px solid pink;
      padding: 20px;
    }

    label {
      display: block;
      height: 80px;
      position: relative;
      text-align-last: justify;
    }

    input {
      height: 30px;
      font-size: 20px;
      padding-left: 20px;
    }

    label>span {
      position: absolute;
      left: 0;
      top: 35px;
      font-size: 20px;
      color: red;
      display: none;
    }
  </style>
</head>

<body>
  <form>
    <label>
      用户名: <input class="username" type="text" />
      <!-- 数字字母开头6～12位 忽略大小写 -->
      <span>请按照规则填写用户名</span>
    </label>
    <label>
      密码: <input class="password" type="text" />
      <!-- 数字字母下划线 6～12位 -->
      <span>请按照规则填写密码</span>
    </label>
    <label>
      手机号: <input class="phone" type="text" />
      <!-- 11位数字即可 -->
      <span>请按照规则填写手机号</span>
    </label>
    <label>
      <!-- 6～12位 开头为数字大小写字母 中间为数字字母下划线均可-->
      <!-- @ 只接收qq 163 sina -->
      <!-- com或者cn -->
      邮箱: <input class="email" type="text" />
      <span>请按照规则填写邮箱</span>
    </label>
    <input type="button" value="完善资料" />
  </form>

  <script>
    // 获取form表单
    let ipts = document.querySelectorAll("form input")

    // 面向对象
    let regObj = {
      username: /^[0-9a-z]\w{5,11}$/i,
      password: /^\w{6,12}$/,
      phone: /^1[3|5|7|8][0-9]{9}$/,
      email: /^[0-9A-Z]\w{5,11}@(qq|163|sina)\.(com|cn)$/
    }

    let spans = document.querySelectorAll("form span")
    ipts.forEach((ele) => {
      ele.onchange = () => {
        let text = ele.value;
        let reg = regObj[ele.className]
        let span = ele.nextElementSibling;
        reg.test(text) ? span.style.display = "none" : span.style.display = "block";
      }
    })





    // formEl.onchange = handlerForm;
    // 事件委托
    /* function handlerForm(e) {
      // 获取事件源
      let target = e.target
      // 通过类名判断当前点击的文本框
      if (e.target.className === "username") {
        handlerCheck(regUsername, target)

      }
      if (e.target.className === "password") {
        handlerCheck(regPassword, target)
      }
      if (e.target.className === "phone") {
        handlerCheck(regPhone, target)
      }
      if (e.target.className === "email") {
        handlerCheck(regEmail, target)
      }
    }
    // 处理校验
    function handlerCheck(reg, target) {
      // 通过校验不显示，否则显示
      reg.test(target.value) ? target.nextElementSibling.style.display = "none" : target.nextElementSibling.style.display = "block"
    } */
  </script>
</body>

</html>